﻿using System;
using System.Linq;
using MessageLib.Frame.Base;

namespace MessageLib.Frame
{
    public class MessageFrame:BaseFrame
    {
        public override byte[] FrameData
        {
            get => _beforeBody.Concat(CommandFrame.FrameData).Concat(_afterBody).ToArray();
            set
            {
                Enumerable.Range(0,7).ToList().ForEach(i=>_beforeBody[i]=value[i]);
                Enumerable.Range(0,245).ToList().ForEach(i=>CommandFrame.FrameData[i] = value[i+7]);
                Enumerable.Range(0,3).ToList().ForEach(i=>_afterBody[i] = value[i+252]);
            }
        }
        private readonly byte[] _beforeBody = new byte[7];
        private readonly byte[] _afterBody = new byte[3];

        public override bool Verify => true;

        public MessageFrame(CommandFrame commandFrame)
        {
            CommandFrame = commandFrame;
	       // DataLength = BitConverter.GetBytes(commandFrame.BodyLength + 3);
        }

        public CommandFrame CommandFrame { get; set; }

        public byte[] Head
        {
            get => new[] {_beforeBody[0], _beforeBody[1], _beforeBody[2]};
            set
            {
                _beforeBody[0] = value[0];
                _beforeBody[1] = value[1];
                _beforeBody[2] = value[2];
            }
        }

        public byte[] Order
        {
            get => new[] {_beforeBody[3]};
            set => _beforeBody[3] = value[0];
        }

        public byte[] Sum
        {
            get => new[] {_beforeBody[4]};
            set => _beforeBody[4] = value[0];
        }

        public byte[] VerifyMethod
        {
            get => new[] {_beforeBody[5]};
            set => _beforeBody[5] = value[0];
        }

        public byte[] DataLength
        {
            get =>new[] {_beforeBody[6]}; 
            set => _beforeBody[6] = value[0];
        }

        public byte[] CommandBody
        {
            get => CommandFrame.FrameData;
            set => CommandFrame.FrameData = value;
        }

        public byte[] VerifyData
        {
            get => new[] {_afterBody[0], _afterBody[1]};
            set
            {
                _afterBody[0] = value[0];
                _afterBody[1] = value[1];
            }
        }

        public byte[] Stop
        {
            get => new[] {_afterBody[2]};
            set => _afterBody[2] = value[0];
        }

	    public static MessageFrame CreateInstance(CommandFrame commandFrame,VerifyMethod verifyMethod)
	    {
		    return new MessageFrame(commandFrame)
		    {
			    Head = new byte[]{0x01,0x02,0x73},
				Order = new byte[] {0x01},
				Sum = new byte[] {0x01},
				VerifyMethod = new [] {(byte)verifyMethod},
				VerifyData = VeriyHelper.Verify(verifyMethod,commandFrame),
				Stop = new byte[] {0x0D}
		    };
	    }
    }
}
